import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'random_joke_provider.dart';

class HomeView extends StatelessWidget {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    final state = context.watch<RandomJokeState>();

    return Scaffold(
      appBar: AppBar(title: const Text('Random Joke Generator')),
      body: SizedBox.expand(
        child: Stack(
          alignment: Alignment.center,
          children: [
            if (state.isRefreshing)
              const Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: LinearProgressIndicator(),
              ),
            Builder(
              builder: (context) {
                if (state.isLoading && !state.hasJoke) {
                  return const CircularProgressIndicator();
                }

                if (state.hasError) {
                  return const Text('Error fetching joke');
                }

                if (state.hasJoke) {
                  final joke = state.joke!;
                  return SelectableText(
                    '${joke.setup}\n\n${joke.punchline}',
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 24),
                  );
                }

                return const SizedBox.shrink();
              },
            ),
            Positioned(
              bottom: 20,
              child: ElevatedButton(
                onPressed: context.read<RefreshJokeCallback>(),
                child: const Text('Get another joke'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
